package com.fxm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fxm.dao.QuestionMapper;
import com.fxm.domain.Option;
import com.fxm.domain.Question;
import com.fxm.returns.RespCode;
import com.fxm.returns.RespEntity;
import com.fxm.returns.RespTable;
import com.fxm.service.OptionService;
import com.fxm.service.QuestionService;
import com.fxm.vo.param.QuestionParam;
import com.fxm.vo.result.QuestionResult;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 答题 服务实现类
 * </p>
 *
 * @author fxm
 * @since 2021-01-07
 */
@Slf4j
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {

    @Autowired
    private OptionService optionService;

    @Override
    public RespTable<List<QuestionResult>> questionList(Integer page, Integer limit, String questionTitle) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Question::getDeleted, 0);
        if (StringUtils.isNotBlank(questionTitle)) {
            queryWrapper.lambda().like(Question::getQuestionTitle, questionTitle);
        }
        IPage<Question> iPage = new Page<>(page, limit);
        IPage<Question> pg = super.page(iPage, queryWrapper);
        List<Question> questionList = pg.getRecords();
        if (Objects.isNull(questionList) || questionList.size() == 0) {
            return new RespTable(RespCode.OK, null, 0);
        }
        //数据组装
        List<QuestionResult> questionResultList = dataPackage(questionList);
        return new RespTable(RespCode.OK, questionResultList, pg.getTotal());
    }

    /**
     * 数据组装
     * @param questionList
     * @return
     */
    private List<QuestionResult> dataPackage(List<Question> questionList) {
        List<QuestionResult> questionResultList = Lists.newArrayList();
        for (Question question : questionList) {
            QuestionResult questionResult = new QuestionResult();
            questionResult.setId(question.getId());
            questionResult.setQuestionTitle(question.getQuestionTitle());
            questionResult.setQuestionType(question.getQuestionType());
            questionResult.setIntegralValue(question.getIntegralValue());

            QueryWrapper<Option> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(Option::getQuestionId, question.getId())
                                 .eq(Option::getDeleted, 0);
            List<Option> optionList = optionService.list(queryWrapper);
            for (Option option : optionList) {
                switch (option.getOptionType()) {
                    case "A" : questionResult.setOptionA(option.getOptionContent()); break;
                    case "B" : questionResult.setOptionB(option.getOptionContent()); break;
                    case "C" : questionResult.setOptionC(option.getOptionContent()); break;
                    case "D" : questionResult.setOptionD(option.getOptionContent()); break;
                }
            }
            questionResultList.add(questionResult);
        }

        return questionResultList;
    }

    @Override
    public RespEntity insertQuestion(QuestionParam questionParam) {
        //添加题目表 数据映射
        Question question = questionDataMapping(questionParam);
        //添加 题目表
        baseMapper.insert(question);
        //添加选项表 数据映射
        List<Option> optionList = optionDateMapping(questionParam, question.getId());
        //批量添加 选项表
        optionService.saveBatch(optionList);
        return new RespEntity(RespCode.SUCCESS);
    }

    /**
     * 添加选项表 数据映射
     * @param questionParam
     * @return
     */
    private List<Option> optionDateMapping(QuestionParam questionParam, Integer id) {
        List<Option> optionList = Lists.newArrayList();

        Option optionA = Option.builder()
                .questionId(id)
                .optionType("A")
                .optionContent(questionParam.getOptionA())
                .build();
        optionList.add(optionA);

        Option optionB = Option.builder()
                .questionId(id)
                .optionType("B")
                .optionContent(questionParam.getOptionB())
                .build();
        optionList.add(optionB);

        Option optionC = Option.builder()
                .questionId(id)
                .optionType("C")
                .optionContent(questionParam.getOptionC())
                .build();
        optionList.add(optionC);

        Option optionD = Option.builder()
                .questionId(id)
                .optionType("D")
                .optionContent(questionParam.getOptionD())
                .build();
        optionList.add(optionD);

        return optionList;
    }

    /**
     * 添加题目表 数据映射
     * @param questionParam
     * @return
     */
    private Question questionDataMapping(QuestionParam questionParam) {
        Question question = Question.builder()
                .questionTitle(questionParam.getQuestionTitle())
                .questionType(questionParam.getQuestionType())
                .integralValue(questionParam.getIntegralValue())
                .build();

        return question;
    }

    @Override
    public RespEntity updateQuestion(QuestionParam questionParam) {
        //编辑题目表 数据映射
        Question question = questionUpdateDM(questionParam);
        //编辑题目
        baseMapper.updateById(question);
        //编辑选项表 数据映射
        List<Option> optionList = optionUpdateDM(questionParam);
        //批量编辑选项表
        optionService.updateBatchById(optionList);
        return new RespEntity(RespCode.SUCCESS);
    }

    /**
     * 编辑选项表 数据映射
     * @param questionParam
     * @return
     */
    private List<Option> optionUpdateDM(QuestionParam questionParam) {
        QueryWrapper<Option> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Option::getQuestionId, questionParam.getId())
                             .eq(Option::getDeleted, 0);
        List<Option> optionList = optionService.list(queryWrapper);

        for (Option option : optionList) {
            if (StringUtils.equals("A", option.getOptionType())) {
                option.setOptionContent(questionParam.getOptionA());
                continue;
            }
            if (StringUtils.equals("B", option.getOptionType())) {
                option.setOptionContent(questionParam.getOptionB());
                continue;
            }
            if (StringUtils.equals("C", option.getOptionType())) {
                option.setOptionContent(questionParam.getOptionC());
                continue;
            }
            if (StringUtils.equals("D", option.getOptionType())) {
                option.setOptionContent(questionParam.getOptionD());
            }
        }

        return optionList;
    }

    /**
     * 编辑题目表 数据映射
     * @param questionParam
     * @return
     */
    private Question questionUpdateDM(QuestionParam questionParam) {
        Question question = baseMapper.selectById(questionParam.getId());
        question.setQuestionTitle(questionParam.getQuestionTitle());
        question.setQuestionType(questionParam.getQuestionType());
        question.setIntegralValue(questionParam.getIntegralValue());
        return question;
    }

    @Override
    public RespEntity deleteQuestion(Integer id) {
        Question question = baseMapper.selectById(id);
        question.setDeleted(1);
        //删除题目表数据
        baseMapper.updateById(question);

        QueryWrapper<Option> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Option::getQuestionId, id)
                             .eq(Option::getDeleted, 0);
        List<Option> optionList = optionService.list(queryWrapper);
        optionList.forEach(option -> {
            option.setDeleted(1);
        });
        //删除选项表数据
        optionService.updateBatchById(optionList);
        return new RespEntity(RespCode.SUCCESS);
    }

    @Override
    public RespEntity batchDeleteQuestion(Integer[] ids) {
        List<Question> questionList = baseMapper.selectBatchIds(Arrays.asList(ids));
        questionList.forEach(question -> {
            question.setDeleted(1);
            //删除题目表数据
            baseMapper.updateById(question);

            QueryWrapper<Option> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(Option::getQuestionId, question.getId())
                                 .eq(Option::getDeleted, 0);
            List<Option> optionList = optionService.list(queryWrapper);
            optionList.forEach(option -> {
                option.setDeleted(1);
            });
            //删除选项表数据
            optionService.updateBatchById(optionList);
        });
        return new RespEntity(RespCode.SUCCESS);
    }
}
